<template>
  <div class="right-center-container">
    <!-- 标题区域 -->
    <div class="title-left">监测点列表</div>

    <div class="monitoring-points-table">
      <!-- 表头 -->
      <div class="table-header">
        <div class="checkbox-cell" />
        <div class="header-cell color-name-cell">
          <span>名称</span>
        </div>
        <div class="header-cell">经度°</div>
        <div class="header-cell">纬度°</div>
        <div class="header-cell">距离m</div>
      </div>

      <!-- 表格内容 -->
      <div class="table-body">
        <div v-for="(point, index) in monitoringPoints" :key="index" class="table-row">
          <div class="checkbox-cell">
            <input :id="'point-' + index" v-model="point.selected" type="checkbox" @change="handlePointSelection(point)" />
            <label :for="'point-' + index" />
          </div>
          <div class="cell name-with-color">
            <div class="color-indicator" :style="{ backgroundColor: point.color }" />
            <span>{{ point.name }}</span>
          </div>
          <div class="cell">{{ formatLng(point.longitude) }}</div>
          <div class="cell">{{ formatLat(point.latitude) }}</div>
          <div class="cell">{{ point.distance }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getRadarPointList } from "@/api/radar/radar-point";
import tokenManager from "@/utils/tokenManager";
export default {
  props: {
    radarId: {
      type: Number,
      default: 6
    }
  },
  data() {
    return {
      // 统一的颜色调色板，与左下曲线图保持一致
      colorPalette: [
        "#00CCFF",
        "#FF6B6B",
        "#4ECDC4",
        "#45B7D1",
        "#96CEB4",
        "#FFEAA7",
        "#DDA0DD",
        "#98D8C8",
        "#FF0000",
        "#00FF00",
        "#0000FF",
        "#FFFF00",
        "#800080",
        "#F7DC6F",
        "#BB8FCE",
        "#85C1E9",
        "#F8C471",
        "#82E0AA",
        "#F1948A",
        "#D7BDE2",
        "#A3E4D7",
        "#F9E79F",
        "#D5A6BD",
        "#AED6F1",
        "#A9DFBF",
        "#FAD7A0",
        "#E8DAEF",
        "#D1F2EB",
        "#FCF3CF",
        "#FADBD8",
        "#D6EAF8",
        "#D5F4E6",
        "#FEF9E7",
        "#EBDEF0",
        "#EAF2F8"
      ],
      monitoringPoints: [],
      pageflag: false,
      timer: null
    };
  },
  computed: {
    selectPointKey() {
      return this.$store.state["xing-bian-screen-setting"].selectPointKey;
    }
  },
  watch: {
    radarId: {
      handler(newRadarId) {
        if (newRadarId) {
          this.getData();
        }
      },
      immediate: false
    },
    selectPointKey: {
      handler(list) {
        if (list.length) {
          this.monitoringPoints = this.monitoringPoints.map(item => {
            return {
              ...item,
              selected: list.includes(Number(item.pointKey))
            };
          });
        }
      },
      immediate: true
    }
  },
  created() {
    this.getData();
    this.timer = setInterval(() => {
      this.getData();
    }, 60000); // 每60秒刷新一次数据
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  mounted() {},
  methods: {
    // 格式化经度显示
    formatLng(lng) {
      const longitude = parseFloat(lng);
      if (isNaN(longitude)) return lng;
      const direction = longitude >= 0 ? "°E" : "°W";
      return Math.abs(longitude).toFixed(6) + direction;
    },

    // 格式化纬度显示
    formatLat(lat) {
      const latitude = parseFloat(lat);
      if (isNaN(latitude)) return lat;
      const direction = latitude >= 0 ? "°N" : "°S";
      return Math.abs(latitude).toFixed(6) + direction;
    },

    async getData() {
      try {
        // 检查token有效性
        if (!tokenManager.isTokenValid()) {
          console.warn("Token无效，跳过数据请求");
          return;
        }

        // 获取监测点列表数据
        const response = await getRadarPointList({
          radarId: this.radarId // 使用props传入的雷达ID
        });

        if (response && response.data && response.data.list) {
          this.processMonitoringPoints(response.data.list);
          this.pageflag = true;
        } else {
          this.pageflag = false;
          // 如果API失败，使用默认数据
          this.initializeMonitoringPoints();
        }
      } catch (error) {
        console.error("获取监测点数据失败:", error);
        this.pageflag = false;
        // 如果API失败，使用默认数据
        this.initializeMonitoringPoints();
      }
    },

    processMonitoringPoints(pointList) {
      // 保存当前选中状态
      const currentSelectedPoints = {};
      this.monitoringPoints.forEach(point => {
        if (point.selected && point.pointIndex) {
          currentSelectedPoints[point.pointIndex] = true;
        }
      });

      this.monitoringPoints = pointList.map((point, index) => ({
        ...point,
        name: point.pointName || point.name || `监测点${index + 1}`,
        longitude: point.lng || point.longitude || point.lon || "0",
        latitude: point.lat || point.latitude || "0",
        distance: point.distance || this.calculateDistance(point),
        // 恢复之前的选中状态
        selected: currentSelectedPoints[point.pointIndex] || false,
        color: this.colorPalette[index % this.colorPalette.length]
      }));

      // 通知其他组件监测点数据已刷新
      this.$root.$emit("monitoring-points-refreshed", this.monitoringPoints);
    },

    calculateDistance(point) {
      // 简单的距离计算，可以根据实际需求调整
      if (point.longitude && point.latitude) {
        // 这里可以实现真实的距离计算逻辑
        // 暂时返回一个模拟值
        return (Math.random() * 2000 + 1000).toFixed(1);
      }
      return "0.0";
    },

    // 初始化监测点数据，为每个点分配不同的颜色（作为备用数据）
    initializeMonitoringPoints() {
      const pointsData = [
        { name: "监测点1", longitude: "116.59435", latitude: "36.275", distance: "1298.8" },
        { name: "监测点2", longitude: "116.59431", latitude: "36.232", distance: "1284.5" },
        { name: "监测点3", longitude: "116.59427", latitude: "36.298", distance: "1274.4" },
        { name: "监测点4", longitude: "116.59426", latitude: "36.262", distance: "1268.0" },
        { name: "监测点5", longitude: "116.59435", latitude: "36.235", distance: "1272.4" },
        { name: "监测点6", longitude: "116.59433", latitude: "36.210", distance: "1267.5" },
        { name: "监测点7", longitude: "116.59432", latitude: "36.285", distance: "1262.6" },
        { name: "监测点8", longitude: "116.59431", latitude: "36.260", distance: "1257.7" },
        { name: "监测点9", longitude: "116.59430", latitude: "36.235", distance: "1252.8" }
      ];

      // 为每个监测点分配不同的颜色
      this.monitoringPoints = pointsData.map((point, index) => ({
        ...point,
        selected: false,
        color: this.colorPalette[index % this.colorPalette.length]
      }));
    },

    handlePointSelection(point) {
      console.log("右中组件 - 监测点选择事件触发:", point);
      console.log("选中状态:", point.selected);
      let selectPointKey = this.$store.state["xing-bian-screen-setting"].selectPointKey;
      console.log(point, "22222");
      if (point.selected) {
        selectPointKey.push(Number(point.pointKey));
      } else {
        selectPointKey = selectPointKey.filter(key => key !== Number(point.pointKey));
      }
      selectPointKey = [...new Set(selectPointKey)];
      this.$store.commit("setSelectPointKey", selectPointKey);
      console.log(selectPointKey, "selectPointKeyselectPointKeyselectPointKey");

      // 发送事件到根组件，通知底部图表组件
      this.$root.$emit("monitoring-point-selected", point);
    }
  }
};
</script>
<style lang="scss" scoped>
.right-center-container {
  height: 100%;
  display: flex;
  flex-direction: column;

  .title-left {
    color: #ffffff;
    font-size: 18px;
    font-weight: bold;
    background-image: url("../../../assets/xing-bian-screen/img/biaoti.png");
    background-size: contain;
    background-repeat: no-repeat;
    background-position: left center;
    padding-left: 60px;
    height: 50px;
    line-height: 50px;
    width: 100%;
    margin: 0;
  }
}

.monitoring-points-table {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(100% - 60px);
  margin-top: 10px;
  width: 100%;
  color: #fff;
  position: relative;
  overflow: hidden; /* 防止内容溢出 */

  .table-header {
    display: flex;
    align-items: center;
    padding: 12px 8px; /* 减少左右内边距 */
    background-color: transparent;
    border-bottom: 2px solid rgba(255, 255, 255, 0.2);

    .header-cell {
      flex: 1;
      text-align: center;
      color: #adeaff;
      font-weight: bold;
      font-size: 14px;

      &.color-name-cell {
        flex: 1.5; /* 减少名称列的宽度 */
        display: flex;
        align-items: center;
        justify-content: center;

        span {
          color: #adeaff;
        }
      }

      &:nth-child(3),
      &:nth-child(4) {
        flex: 1.5; /* 减少经纬度列的宽度 */
      }

      &:nth-child(5) {
        flex: 1;
      }
    }

    .checkbox-cell {
      width: 30px; /* 减少复选框列宽度 */
      text-align: center;
    }
  }

  .table-body {
    flex: 1;
    overflow-y: auto;

    .table-row {
      display: flex;
      align-items: center;
      padding: 8px 8px; /* 减少左右内边距 */
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      &:hover {
        background-color: rgba(0, 40, 77, 0.3);
      }

      .cell {
        flex: 1;
        text-align: center;
        color: #ffffff;

        &.name-with-color {
          flex: 1.5; /* 与表头保持一致 */
          display: flex;
          align-items: center;
          justify-content: flex-start;
          gap: 8px;
          padding-left: 15px; /* 减少左内边距 */

          .color-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            border: 1px solid rgba(255, 255, 255, 0.3);
            flex-shrink: 0;
          }

          span {
            color: #ffffff;
          }
        }

        &:nth-child(3),
        &:nth-child(4) {
          flex: 1.5; /* 与表头保持一致 */
        }

        &:nth-child(5) {
          flex: 1;
        }
      }

      .color-cell {
        display: flex;
        justify-content: center;
        align-items: center;
        flex: 0 0 30px !important; /* 与表头保持一致 */
      }

      .color-indicator {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        border: 1px solid rgba(255, 255, 255, 0.3);
      }

      .checkbox-cell {
        width: 30px; /* 与表头保持一致 */
        text-align: center;

        input[type="checkbox"] {
          appearance: none;
          -webkit-appearance: none;
          width: 16px;
          height: 16px;
          border: 1px solid #00ccff;
          border-radius: 2px;
          background-color: transparent;
          position: relative;
          cursor: pointer;
          vertical-align: middle;

          &:checked {
            background-color: #00ccff;

            &:after {
              content: "";
              position: absolute;
              left: 5px;
              top: 2px;
              width: 4px;
              height: 8px;
              border: solid white;
              border-width: 0 2px 2px 0;
              transform: rotate(45deg);
            }
          }
        }
      }
    }
  }
}
</style>
